package algorithm;

import java.util.Arrays;

/**
 * 977. 有序数组的平方
 * @author Panbo Guo
 * @date 2021/7/8
 */
public class T00977 {

    public static void main(String[] args) {
        int[] nums = {-3,-2,-1,0};
        System.out.println(Arrays.toString(new Solution().sortedSquares(nums)));
    }

    static class Solution {
        public int[] sortedSquares(int[] nums) {
            if (nums.length == 1) {
                return new int[]{nums[0] * nums[0]};
            }
            final int length = nums.length;
            int[] resArr = new int[length];
            int left = 0, right = 0;
            for (int num : nums) {
                if (num < 0) {
                    right ++;
                } else {
                    break;
                }
            }
            left = right - 1;
            int index = 0;
            while (left >= 0 || right < length) {
                if (right >= length) {
                    resArr[index ++] = nums[left] * nums[left];
                    left --;
                } else if (left < 0) {
                    resArr[index ++] = nums[right] * nums[right];
                    right ++;
                } else {
                    if ((-nums[left]) < nums[right]) {
                        resArr[index++] = nums[left] * nums[left];
                        left--;
                    } else {
                        resArr[index++] = nums[right] * nums[right];
                        right++;
                    }
                }
            }
            return resArr;
        }
    }
}
